<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue';
import { $t } from '@vben/locales';

import type { UserHasGroup } from '../user_has_group/types';
import type { UctooUser } from './types';
import { onMounted, reactive, ref, watch } from 'vue';
import { message } from 'ant-design-vue';

import { adductooUserHasGroup, edituctooUserHasGroup } from '../user_has_group/api';
import { getUserGroupList, connectUserHasGroup } from '../user_has_group/homeapi';
import { removeEmpty } from '#/utils/common';
import { useDebounceFn } from '@vueuse/core';
import { getUserGroupAll } from '../user_group/homeapi';

const loading = ref(false);

const props = defineProps<{
  mode: 'add' | 'edit' | 'permission';
  record: UctooUser | null;
  visible: boolean;
}>();

const emit = defineEmits(['update:visible', 'success']);

const formRef = ref<FormInstance>();
const formState = reactive<Partial<UserHasGroup>>({
groupable_id:'',
groupable_type:'',
group_id:'',
status:1,
});
 

/** rules */
const rules = {
 groupable_id: [{ message: '不能为空', required: true }],
 groupable_type: [{ message: '不能为空', required: false }],
 group_id: [{ message: '不能为空', required: true }],
 status: [{ message: '不能为空', required: true }],
};


watch(
  () => props.record,
  (newVal) => {
    console.log(props.record);
    formState.groupable_id = props.record?.id;
    formState.groupable_type = "uctoo_user";
    formState.group_id = props.record?.groups[0]?.group_id;
    formState.status = props.record?.groups[0]?.status ? props.record?.groups[0]?.status : 1;
  },
  { immediate: true },
);

const handleOk = () => {
  console.log(formState);
    interface Formated {
      id?:string,
      groupable_id?: string,
      groupable_type?: string,
      group_id?: string,
      status?: number,
     };

    const formatedFormState: Formated = {
      id: formState.id,
      groupable_id: formState.groupable_id,
      groupable_type: formState.groupable_type,
      group_id: formState.group_id,
      status: Number(formState.status),
     };

  formRef.value?.validate().then(async () => {
    try {
      if (props.mode === 'add') {
        delete formatedFormState['id'];
        await connectUserHasGroup(removeEmpty(formatedFormState));
        message.success('添加成功');
      } else {
        await connectUserHasGroup(removeEmpty(formatedFormState));
        message.success('编辑成功');
      }
      emit('success');
    } catch {
      message.error('操作失败');
    }
  });
};

const handleCancel = () => {
  emit('update:visible', false);
};

const groupOptions = ref<any[]>([]);

const rawSearch = async (searchText: string) => {
  if (!searchText) {
    groupOptions.value = [];
    return;
  }

  loading.value = true;
  try {
    const res = await getUserGroupList(0, 50, { group_name: searchText });
    console.log('搜索结果:', res);

    const validDatas = res.userGroups.filter(
      (item) => item.deleted_at === null,
    );
    groupOptions.value = validDatas.map((item) => ({
      label: item.group_name,
      value: item.id,
    }));
  } catch (error) {
    console.error('搜索错误:', error);
    message.error('获取用户列表失败');
    groupOptions.value = [];
  } finally {
    loading.value = false;
  }
};

const onSearch = useDebounceFn(rawSearch, 500);

const fetchData = async () => {
  loading.value = true;
  try {
    const resUserGroupAll = await getUserGroupAll();
    console.log(resUserGroupAll);
    groupOptions.value = resUserGroupAll.map((item) => ({
      label: item.group_name,
      value: item.id,
    }));
  } catch {
    message.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <a-modal
    :open="visible"
    :title="mode === 'add' ? '新增' : '编辑'"
    @cancel="handleCancel"
    @ok="handleOk"
  >

  <a-form ref="formRef" :model="formState" :rules="rules">
<a-form-item :label="$t('database_column.user_has_group.groupable_id')" name="groupable_id" v-show="false">
        <a-input v-model:value="formState.groupable_id" />
      </a-form-item><a-form-item :label="$t('database_column.user_has_group.groupable_type')" name="groupable_type"  v-show="false">
        <a-input v-model:value="formState.groupable_type" />
      </a-form-item><a-form-item :label="$t('database_column.user_has_group.group_id')" name="group_id">
        <a-select
          v-model:value="formState.group_id"
          show-search
          :options="groupOptions"
          @search="onSearch"
          :default-active-first-option="false"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="loading ? '加载中...' : '没有更多选项'"
        />
      </a-form-item><a-form-item :label="$t('database_column.user_has_group.status')" name="status"  v-show="false">
        <a-input v-model:value="formState.status" />
      </a-form-item></a-form>

  </a-modal>
</template>
